package com.topboya.linker.ui.activity;

import android.content.Context;
import android.content.Intent;
import android.graphics.Color;
import android.graphics.drawable.Drawable;
import android.support.v4.view.ViewCompat;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.view.Gravity;
import android.view.KeyEvent;
import android.view.View;
import android.view.ViewGroup;
import android.view.inputmethod.InputMethodManager;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.google.android.flexbox.FlexboxLayout;
import com.topboya.linker.AppConst;
import com.topboya.linker.R;
import com.topboya.linker.diyview.CenteredEditText;
import com.topboya.linker.model.DataManagerbo;
import com.topboya.linker.model.levelitem.DepartmentGroupBo;
import com.topboya.linker.model.response.DeptUserResponse;
import com.topboya.linker.ui.adapter.DeptUserAdapter;
import com.topboya.linker.ui.adapter.RecycleViewDivider;
import com.topboya.linker.ui.base.Presenter.BasePresenter;
import com.topboya.linker.ui.base.activity.BaseActivity;
import com.topboya.linker.utils.AndroidUtils;
import com.topboya.linker.utils.LogUtils;

import java.util.ArrayList;
import java.util.LinkedHashMap;
import java.util.List;

public class SelectTeamActivity extends BaseActivity {

    private static final String TAG = "SelectTeamActivity:";
    private CenteredEditText search;
    private FlexboxLayout flex_departnames_contents;
    private CheckBox ck_selectall;
    private RecyclerView ry_team;
    private TextView tv_selected_team_num;
    private Button btn_selected;
    private List<DeptUserResponse.Data> mData;
//    private SelecteamAdapter selecteamAdapter;
   private  DeptUserAdapter deptUserAdapter;
//    List<DepartmentGroupBo> departmentGroupBos;
   private  List<DepartmentGroupBo> departmetGroupList;
   private RelativeLayout rl_follow_head;
    //     用来保存选中的成员，后面的搜索功能更好处理一点
    private LinkedHashMap<String ,DepartmentGroupBo> selectedDepartLinkHashList = new LinkedHashMap<>();

    @Override
    protected int getLayoutId() {

        return R.layout.activity_select_team;
    }

    @Override
    protected void initView() {

        search = findViewById(R.id.search);
        flex_departnames_contents = findViewById(R.id.flex_departnames_contents);
        ck_selectall = findViewById(R.id.ck_selectall);
        ry_team = findViewById(R.id.ry_team);
        tv_selected_team_num = findViewById(R.id.tv_selected_team_num);
        btn_selected = findViewById(R.id.btn_selected);
        flex_departnames_contents.addView(createNewFlexItemTextView("Linker"));
    }


    private TextView createNewFlexItemTextView( String textname) {

        TextView textView = new TextView(this);
        textView.setGravity(Gravity.CENTER);
        textView.setText(textname);
        textView.setTextSize(16);
        textView.setTextColor(getResources().getColor(R.color.home_bottom_text_checked));
        if (flex_departnames_contents.getChildCount() >= 1){

            Drawable drawable = getResources().getDrawable(R.drawable.rightarrow);
            drawable.setBounds(0,0, drawable.getMinimumWidth(), drawable.getMinimumHeight());
            textView.setCompoundDrawables(drawable,null,null,null);
            textView.setCompoundDrawablePadding(AndroidUtils.dpToPixel(this,10));
        }
        textView.setOnClickListener(view -> {

            int index = flex_departnames_contents.indexOfChild(view);
            int totalcount = flex_departnames_contents.getChildCount();
            for (int i=totalcount;index !=0 && i>index;i--){

                departmetGroupList =departmetGroupList.get(0).getDepartmentGroupBosPs();
                LogUtils.v(TAG + "i:"+i);
                int totalcountremvoe = flex_departnames_contents.getChildCount();
                flex_departnames_contents.removeViewAt(totalcountremvoe-1);
            }
               if (flex_departnames_contents.getChildCount() ==1){

                flex_departnames_contents.setVisibility(View.GONE);
               }

               deptUserAdapter.setNewData(departmetGroupList);

        });
//        int padding = AndroidUtils.dpToPixel(this, 4);
//        int paddingLeftAndRight = AndroidUtils.dpToPixel(this, 8);
//        ViewCompat.setPaddingRelative(textView, paddingLeftAndRight, padding, paddingLeftAndRight, padding);
        FlexboxLayout.LayoutParams layoutParams = new FlexboxLayout.LayoutParams(
                ViewGroup.LayoutParams.WRAP_CONTENT,
                ViewGroup.LayoutParams.WRAP_CONTENT);
        int margin = AndroidUtils.dpToPixel(this, 20);
        int marginTop = AndroidUtils.dpToPixel(this, 10);
        layoutParams.setMargins(marginTop, marginTop, 0, marginTop);
        textView.setLayoutParams(layoutParams);
        return textView;
    }
    @Override
    protected void initData() {

        mData = (List<DeptUserResponse.Data>) getIntent().getSerializableExtra("mData");
        RecyclerView.LayoutManager layoutManager = new LinearLayoutManager(this, LinearLayoutManager.VERTICAL, false);
        ry_team.setLayoutManager(layoutManager);
        ry_team.addItemDecoration(new RecycleViewDivider(this, LinearLayoutManager.HORIZONTAL, 2, 0xBFC0C2));
        DataManagerbo dataManager = new DataManagerbo(mData);
        departmetGroupList = dataManager.getCompanydata();
//        设置每一页孩子的总数
         for (DepartmentGroupBo departmentGroupBos:departmetGroupList){
             ArrayList<DepartmentGroupBo> selectdepts = new ArrayList();
             selectdepts.clear();
             getALLOfChildDeptsSize(departmentGroupBos.getDepartmentGroupBosCd(), selectdepts);
             departmentGroupBos.setTotalnum(String.valueOf(selectdepts.size()));
         }

//        departmentGroupBos = new ArrayList<>();
//        departmentGroupBos.addAll(departmetGroupList);
//        selecteamAdapter = new SelecteamAdapter(departmentGroupBos);
        deptUserAdapter = new DeptUserAdapter(departmetGroupList);
        ry_team.setAdapter(deptUserAdapter);

        deptUserAdapter.setOnItemClickListener((adapter, view, position) -> {


            if (null==departmetGroupList.get(position).getDepartmentGroupBosCd() ||0== departmetGroupList.get(position).getDepartmentGroupBosCd().size()){

//                UIUtils.showToast("到底了");

            }else {
                if (departmetGroupList.get(position).isSub()){

                    flex_departnames_contents.setVisibility(View.VISIBLE);
                    flex_departnames_contents.addView(createNewFlexItemTextView(departmetGroupList.get(position).getDeparemtname()));

                }
                departmetGroupList =departmetGroupList.get(position).getDepartmentGroupBosCd();

                for (DepartmentGroupBo departmentGroupBos:departmetGroupList){
                    ArrayList<DepartmentGroupBo> selectdepts = new ArrayList();
                    selectdepts.clear();
                     getALLOfChildDeptsSize(departmentGroupBos.getDepartmentGroupBosCd(),selectdepts);
                    departmentGroupBos.setTotalnum(String.valueOf(selectdepts.size()));
                }
                for (DepartmentGroupBo departmentGroupBos:departmetGroupList){

                    ArrayList<DepartmentGroupBo> selectdepts = new ArrayList();
                    selectdepts.clear();
                    getAllSelectDepts(departmentGroupBos.getDepartmentGroupBosCd(),selectdepts);
                    departmentGroupBos.setSelectedNum(String.valueOf(selectdepts.size()));
                }

                deptUserAdapter.setNewData(departmetGroupList);

            }

        });

        deptUserAdapter.setOnItemChildClickListener((adapter, view, position) -> {
            switch (view.getId()){

                case R.id.ck_select:

                    boolean ischecked = this.departmetGroupList.get(position).isCheked();
                    LogUtils.v(TAG + "ischecked:"+ischecked);
                    this.departmetGroupList.get(position).setCheked(!ischecked);
//                    for循环遍历当前组所有的，如果都为true，则全部选中
                    for (int i=0;i < departmetGroupList.size(); i++){
                        LogUtils.v(TAG +"departmetGroupList.toSrring:"+departmetGroupList.get(i).getDeparemtname());
                        LogUtils.v(TAG + "departmetGroupList.get(position).Checked:"+departmetGroupList.get(i).isCheked());
                        if (!departmetGroupList.get(i).isCheked()){

                            ck_selectall.setChecked(false);
                            break;
                        }else {
                            ck_selectall.setChecked(true);
                        }
                    }
                    List<DepartmentGroupBo> departmentGroupBosch = this.departmetGroupList.get(position).getDepartmentGroupBosCd();
                    //  递归调用，将选中的所有孩子都设置成和父结点相同的状态,
                    setAllDepOfChildStatus(departmentGroupBosch,!ischecked);
                    //  如果在中间层次的话，将他的父状态也设置为选中状态
                    for (DepartmentGroupBo departmentGroupBos:departmetGroupList){

                        ArrayList<DepartmentGroupBo> selectdepts = new ArrayList();
                        selectdepts.clear();
                        getAllSelectDepts(departmentGroupBos.getDepartmentGroupBosCd(),selectdepts);
                        departmentGroupBos.setSelectedNum(String.valueOf(selectdepts.size()));
                    }
                    setTextViewSelectednum();

                    deptUserAdapter.setNewData(departmetGroupList);

                    break;
            }
        });
    }
    private void setAllDepOfParentStatus(DepartmentGroupBo departmentGroupBos, boolean ishecked) {

        while (null !=departmentGroupBos){
            departmentGroupBos.setCheked(ishecked);
            departmentGroupBos = departmentGroupBos.getDepartmentGroupBoP();
        }
    }

    private void setAllDepOfChildStatus(List<DepartmentGroupBo> departmentGroupBo,boolean ischecked){

        for (DepartmentGroupBo departmentGroup: departmentGroupBo) {
            departmentGroup.setCheked(ischecked);
            setAllDepOfChildStatus(departmentGroup.getDepartmentGroupBosCd(), ischecked);
        }
    }

    public  void getAllSelectDepts(List<DepartmentGroupBo> departmentGroupBo,List<DepartmentGroupBo> selectdepts){

        for (DepartmentGroupBo departmentGroup: departmentGroupBo) {

            if (!departmentGroup.isSub() && departmentGroup.isCheked()){
                selectdepts.add(departmentGroup);
            }
            getAllSelectDepts(departmentGroup.getDepartmentGroupBosCd(),selectdepts);

        }
    }
    public  void getAllSearchDepts(List<DepartmentGroupBo> departmentGroupBo,List<DepartmentGroupBo> selectdepts,String searchKey){

        for (DepartmentGroupBo departmentGroup: departmentGroupBo) {

            if (!departmentGroup.isSub() && departmentGroup.getDeparemtname().contains(searchKey)){
                selectdepts.add(departmentGroup);
            }
            getAllSearchDepts(departmentGroup.getDepartmentGroupBosCd(),selectdepts,searchKey);

        }

    }
//    得到当前节点所有子节点为部门成员的个数
public void  getALLOfChildDeptsSize(List<DepartmentGroupBo> departmentGroupBo,List<DepartmentGroupBo> selectdepts){

    for (DepartmentGroupBo departmentGroup: departmentGroupBo) {

        if (!departmentGroup.isSub()){
//            LogUtils.v(TAG + "departmentGroup.getDeparemtname()"+departmentGroup.getDeparemtname());
            selectdepts.add(departmentGroup);
        }
        getALLOfChildDeptsSize(departmentGroup.getDepartmentGroupBosCd(),selectdepts);
    }

}

    public static void hideKeyboard(View view) {

        InputMethodManager manager = (InputMethodManager) view.getContext()
                .getSystemService(Context.INPUT_METHOD_SERVICE);
        manager.hideSoftInputFromWindow(view.getWindowToken(), 0);
    }
    @Override
    protected void initListener() {

        search.setOnEditorActionListener((v, actionId, event) ->{

            String searchKey =  v.getText().toString().trim();
            hideKeyboard(search);
            searchName(searchKey);

             return false;

        });
       ck_selectall.setOnClickListener((buttonView) -> {

         boolean isChecked =  ck_selectall.isChecked();
//            全选事件
           for (int i =0;i < departmetGroupList.size();i++){

               departmetGroupList.get(i).setCheked(isChecked);
               List<DepartmentGroupBo> departmentGroupBosch = departmetGroupList.get(i).getDepartmentGroupBosCd();
               //  递归调用，将选中的所有孩子都设置成和父结点相同的状态,
               setAllDepOfChildStatus(departmentGroupBosch,isChecked);
               //  如果在中间层次的话，将他的父状态也设置为选中状态
           }
           for (DepartmentGroupBo departmentGroupBos:departmetGroupList){

               ArrayList<DepartmentGroupBo> selectdepts = new ArrayList();
               selectdepts.clear();
               getAllSelectDepts(departmentGroupBos.getDepartmentGroupBosCd(),selectdepts);
               departmentGroupBos.setSelectedNum(String.valueOf(selectdepts.size()));
           }

           setTextViewSelectednum();
           deptUserAdapter.setNewData(departmetGroupList);
       });

        btn_selected.setOnClickListener(v -> {

//              拿到选取的所有成员，从第一层开始遍历
//            界面有可能不在第一层，所以要先拿到第一层数据
            List<DepartmentGroupBo> departmentGroupBosroot = new ArrayList<>();
            departmentGroupBosroot.clear();
            departmentGroupBosroot.addAll(departmetGroupList);
            while (true){
                if (null==departmentGroupBosroot.get(0).getDepartmentGroupBosPs()){

//                    得到根节点；开始遍历成员为true的
                    ArrayList<DepartmentGroupBo> selectdepts = new ArrayList();
                    selectdepts.clear();
                    getAllSelectDepts(departmentGroupBosroot,selectdepts);
                    LogUtils.v(TAG+"getDeparemtname()"+selectdepts.toString());
                    //数据是使用Intent返回
                    Intent intent = new Intent();
                    //把返回数据存入Intent
//                    intent.putExtra("selectdepts", selectdepts);
                    AppConst.SELECTED_MEMBER = selectdepts;
                    //设置返回数据
                    setResult(1002, intent);
                    //关闭Activity
                    finish();
                     break;
                }else {
                    departmentGroupBosroot = departmentGroupBosroot.get(0).getDepartmentGroupBosPs();
                }
            }
        });

    }

    private void setTextViewSelectednum() {

        List<DepartmentGroupBo> departmentGroupBosroot = new ArrayList<>();
        departmentGroupBosroot.clear();
        departmentGroupBosroot.addAll(departmetGroupList);
        while (true){
            if (null==departmentGroupBosroot.get(0).getDepartmentGroupBosPs()){

//                    得到根节点；开始遍历成员为true的
                ArrayList<DepartmentGroupBo> selectdepts = new ArrayList();
                selectdepts.clear();
                getAllSelectDepts(departmentGroupBosroot,selectdepts);
               tv_selected_team_num.setText("已选择："+selectdepts.size()+"人");
                break;
            }else {
                departmentGroupBosroot = departmentGroupBosroot.get(0).getDepartmentGroupBosPs();
            }
        }
    }

    private void searchName(String searchKey) {

        List<DepartmentGroupBo> departmentGroupBosroot = new ArrayList<>();
        departmentGroupBosroot.clear();
        departmentGroupBosroot.addAll(departmetGroupList);
        while (true){
            if (null==departmentGroupBosroot.get(0).getDepartmentGroupBosPs()){

//                    得到根节点；开始遍历成员为true的
                ArrayList<DepartmentGroupBo> selectdepts = new ArrayList();
                selectdepts.clear();
                getAllSearchDepts(departmentGroupBosroot,selectdepts,searchKey);
                deptUserAdapter.setNewData(selectdepts);
                LogUtils.v(TAG + "selectdepts:"+selectdepts.toString());
                break;
            }else {
                departmentGroupBosroot = departmentGroupBosroot.get(0).getDepartmentGroupBosPs();
            }
        }
    }




    @Override
    protected BasePresenter createPresenter() {

        return null;
    }



    @Override
    public void onBackPressed() {

        back();
    }

    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {
        // 是否触发按键为back键
        if (keyCode == KeyEvent.KEYCODE_BACK) {
            onBackPressed();
            return true;
        } else { // 如果不是back键正常响应
            return super.onKeyDown(keyCode, event);
        }
    }

    private void back() {

        if (null==departmetGroupList.get(0).getDepartmentGroupBosPs()||0== departmetGroupList.get(0).getDepartmentGroupBosPs().size()){
//            UIUtils.showToast("到头了");
            super.onBackPressed();
        }else {

//            再返回的时候，遍历当层是否有选中的状态如果有那么父亲也设置为选中状态；
            boolean ischecked = false;
            for (int i=0;i < departmetGroupList.size(); i++){
                if (departmetGroupList.get(i).isCheked()){
                    ischecked = true;
                    if (i == departmetGroupList.size()-1){
//                        这里判断是否遍历到最后一个，遍历到最后一个表示所有的都已经选中了，则全选按钮也要更新
                         ck_selectall.setChecked(ischecked);
                    }
                    break;

                }else {

                    ischecked = false;
                    ck_selectall.setChecked(ischecked);
                }
            }
            LogUtils.v(TAG+ "ischecked:"+ischecked);
            DepartmentGroupBo departmentGroupBosp = this.departmetGroupList.get(0).getDepartmentGroupBoP();
            departmetGroupList =departmetGroupList.get(0).getDepartmentGroupBosPs();
            if (departmentGroupBosp !=null) setAllDepOfParentStatus(departmentGroupBosp,ischecked);

            for (DepartmentGroupBo departmentGroupBos:departmetGroupList){

                ArrayList<DepartmentGroupBo> selectdepts = new ArrayList();
                selectdepts.clear();
                getAllSelectDepts(departmentGroupBos.getDepartmentGroupBosCd(),selectdepts);
                departmentGroupBos.setSelectedNum(String.valueOf(selectdepts.size()));
            }
            deptUserAdapter.setNewData(departmetGroupList);

            flex_departnames_contents.removeViewAt(flex_departnames_contents.getChildCount() -1);
            if (flex_departnames_contents.getChildCount()==1){

                    flex_departnames_contents.setVisibility(View.GONE);
            }
        }
    }
}
